//
//  SinaTabBar.swift
//  SinaWeibo(Swift)
//
//  Created by 王忠迪 on 9/22/16.
//  Copyright © 2016 王忠迪. All rights reserved.
//

import UIKit

class SinaTabBar: UITabBar {
    
    var composeClosure: (() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(composeBtn)
        
        composeBtn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
        
    }
    
    //按钮点击事件
    func composeBtnClick() {
        //这里的点击事件需要控制器去执行,所以使用闭包
        composeClosure?()
    }
    
    //这里由于已经确定要使用纯代码写SinaTabBar,所以如果有人使用xib或sb加载会执行这个方法,导致崩溃
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let kWidth = self.bounds.width / 5
        
        let kHeight = self.bounds.height
        
        var index = 0
        
        for subView in self.subviews {
            //NSClassFromString("UITabBarButton")! 这是判断的关键,千万不能写错了
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                subView.frame = CGRect(x: CGFloat(index) * kWidth, y: 0, width: kWidth, height: kHeight)
                index += (index == 1 ? 2 : 1)
                
            }
        }
        
        self.composeBtn.center = CGPoint(x: self.center.x, y: self.bounds.height * 0.5)
        self.composeBtn.bounds.size = CGSize(width: kWidth, height: kHeight)
        
    }
    
    //添加按钮(通过懒加载的方式)
    lazy var composeBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
//        btn.sizeToFit()
        return btn
    }()
    
    
}
